package com.base.pub.interceptor;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.dragonnova.business.model.User;
import org.dragonnova.business.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.base.pub.web.BaseController;

public class MobileInterceptor extends BaseController implements HandlerInterceptor {
	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String requestURI = request.getServletPath();
		if (requestURI.contains("webSocket") || requestURI.contains("login.html")) {
			return true;
		} else {
			User user = getLoginUser(session);
			if (user != null && session.getId().equals(user.getSessionId())) {
				return true;
			} else {
				doLogin(request, response);
				return false;
			}
		}
	}

	/**
	 * 自动登录
	 * 
	 * @param request
	 * @param response
	 */
	private void doLogin(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookies = request.getCookies();
		HttpSession session = request.getSession();
		if (cookies != null) {
			String userName = " ", password = " ";
			for (Cookie cookie : cookies) {
				if ("userName".equals(cookie.getName())) {
					userName = cookie.getValue();
				}
				if ("sessionId".equals(cookie.getName())) {
					password = cookie.getValue();
				}
			}
			try {
				User user = userService.findAdminByName(userName);
				if (user != null && password.equals(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))) {
					user.setPassword("");
					setLoginUser(session, user);
					gotoPage( request,  response,"/lable.html");
				}else{
					gotoPage( request,  response,"/login.html");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			gotoPage( request,  response,"/login.html");
		}
	}

	private void gotoPage(HttpServletRequest request, HttpServletResponse response,String pageName) {
		String loginUrl = request.getContextPath();
		loginUrl += pageName;
		try {
			response.sendRedirect(loginUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
